<template>
  <n-layout style="height: 100%">
    <n-layout-header style="height: 64px; padding-left: 24px; padding-top: 15px;" bordered>
      <n-form ref="formRef" label-placement="left" inline :label-width="80" :model="formValue" :rules="rules">
        <n-form-item path="name">
          <n-input v-model:value="formValue.name" placeholder="" />
        </n-form-item>
        <n-form-item>
          <n-space>
            <n-button @click="saveConfig" type="info">
              保存配置
            </n-button>
            <n-button @click="initConfig" type="info">
              刷新配置
            </n-button>
            <n-button @click="initData" type="info">
              刷新数据
            </n-button>
            <div>普通报表</div>
            <div>分组报表</div>
            <div>交叉报表</div>
          </n-space>
        </n-form-item>
      </n-form>
    </n-layout-header>
    <n-layout has-sider position="absolute" style="top: 64px">
      <n-layout-sider bordered content-style="padding: 15px;" :width="150">
        <n-collapse v-model:expanded-names="cia">
          <n-collapse-item :title="`字符串（${options.length || 0}）`" name="1">
            <draggable group="demo1" :sort="false" :fallback-on-body="false" :fallback-class="false" :list="options"
              @start="onStart" itemKey="name" handle=".move" animation="300">
              <template #item="{ element }">
                <div class="move mb-1" :dragindex="`${element.index}`">
                  <n-button class="w-full" strong secondary type="info">
                    {{ element.name }}
                  </n-button>
                </div>
              </template>
            </draggable>
          </n-collapse-item>
        </n-collapse>
      </n-layout-sider>
      <n-layout has-sider sider-placement="right">
        <n-layout-content>
          <div id="luckysheet"></div>
        </n-layout-content>
        <n-layout-sider bordered content-style="padding: 15px;" :width="180">
          <n-collapse v-model:expanded-names="cia1">
            <n-collapse-item title="基本信息" name="1">
              <n-form ref="formRef" label-placement="top" label-align="left" :label-width="40" :model="cellBody"
                size="small">
                <n-form-item label="坐标" path="position">
                  <n-input :value="`${(cellBody.position.r || 0) + 1},${(cellBody.position.c || 0) + 1}`"
                    :disabled="true" />
                </n-form-item>
                <n-form-item label="值" path="value">
                  <n-input :value="`${cellBody.cell.m || ''}`" placeholder="" />
                </n-form-item>
                <n-form-item label="宽度" path="width">
                  <n-input :value="`${(cellBody.position.end_c || 0) - (cellBody.position.start_c || 0) - 1}`"
                    placeholder="Input width" />
                </n-form-item>
                <n-form-item label="高度" path="height">
                  <n-input :value="`${(cellBody.position.end_r || 0) - (cellBody.position.start_r || 0) - 1}`"
                    placeholder="Input height" />
                </n-form-item>
              </n-form>
            </n-collapse-item>
            <n-collapse-item title="基础配置" name="2">
              <n-form ref="formRef" label-placement="top" label-align="left" :label-width="40" :model="cellBody"
                size="small">
                <n-form-item label="聚合方式" path="juhe">
                  <n-select v-model:value="cellBody.cell.agg"
                    :options="[{ label: 'list', value: 'list' }, { label: 'group', value: 'group' }]" />
                </n-form-item>
                <n-form-item label="方向" path="juhe">
                  <n-select v-model:value="cellBody.cell.cro"
                    :options="[{ label: 'down', value: 'down' }, { label: 'right', value: 'right' }]" />
                </n-form-item>
              </n-form>
            </n-collapse-item>
            <n-collapse-item title="条件属性" name="3">
              <!-- <n-form ref="formRef" label-placement="top" label-align="left" :label-width="40" :model="cellBody"
                size="small">
                <n-form-item label="关联" path="juhe">
                  <n-select :value="`${cellBody.cell.format || ''}`" placeholder="Input format" />
                </n-form-item>
              </n-form> -->
            </n-collapse-item>
          </n-collapse>
        </n-layout-sider>
      </n-layout>
    </n-layout>
  </n-layout>
</template>

<script setup>
import { ref, onMounted, watch } from "vue";
import draggable from "vuedraggable";

const formValue = ref({});
const rules = ref({});

const cellBody = ref({
  cell: {},
  position: {},
});

const cia = ref("1");
const cia1 = ref(["1", "2"]);

const options = [
  { index: '1', name: "用户编码", key: '1', source: 'q' },
  { index: '2', name: "登录帐号", key: '2', source: 'q' },
  { index: '3', name: "入库时间", key: '3', source: 'q' },
];

const dragTargetNode = ref({});

// !!! create luckysheet after mounted
onMounted(() => {
  document.body.ondrop = function (event) {
    event.preventDefault();
    event.stopPropagation();
  };
  // 获取设计器
  initConfig();

});

//拖拽开始的事件
const onStart = (node) => {
  if (!node) {
    return;
  }
  // console.log("开始拖拽", node);
  // dragTargetNode.value.name = node.item.attributes.dragdata.value;
  dragTargetNode.value = options.filter(item => item.index === node.item.attributes.dragindex.value)[0];
  // console.log('移动的数据是', dragTargetNode.value)
};

const saveConfig = () => {
  if (!luckysheet) {
    return;
  }
  const sheetData = luckysheet.getSheetData([0]);
  const config = luckysheet.getConfig([0]);
  // // const allSheets = luckysheet.getAllSheets()[0];
  console.log(JSON.stringify(sheetData));
  localStorage.setItem('LUCKSHEET_SHEETDATA', JSON.stringify(sheetData));
  localStorage.setItem('LUCKSHEET_CONFIG', JSON.stringify(config));
}

const initConfig = (sheetDataValue) => {
  const sheetData = JSON.parse(localStorage.getItem('LUCKSHEET_SHEETDATA')) || [];
  const config = JSON.parse(localStorage.getItem('LUCKSHEET_CONFIG')) || {};
  console.log(sheetData)
  console.log(config)
  // luckysheet create
  luckysheet.create({
    container: "luckysheet",
    lang: "zh",
    showGridLines: true,
    allowEdit: true,
    showinfobar: false, // 是否显示顶部信息栏
    showsheetbar: false, // 是否显示底部sheet页按钮
    showstatisticBar: false, // 是否显示底部计数栏
    sheetBottomConfig: true, // sheet页下方的添加行按钮和回到顶部按钮配置
    userInfo: false, // 右上角的用户信息展示样式
    enableAddRow: false,
    enableAddBackTop: false,
    row: 60,
    column: 32,
    protection: false,
    showtoolbarConfig: {
      chart: false, // '图表'（图标隐藏，但是如果配置了chart插件，右击仍然可以新建图表）
      postil: false, //'批注'
      pivotTable: false, //'数据透视表'
      textRotateMode: false, // '文本旋转方式'
      image: false,
      link: false,
      print: false, // '打印'
      protection: false, // '工作表保护'
    },
    cellRightClickConfig: {
      chart: false, // 图表生成
      image: false, // 插入图片
      link: false, // 插入链接
    },
    showstatisticBarConfig: {
      count: true,
      view: true,
      zoom: true,
    },
    showsheetbarConfig: {
      add: false, //新增sheet
      menu: false, //sheet管理菜单
      sheet: false, //sheet页显示
    },
    pager: {
      pageIndex: 1, //当前的页码
      pageSize: 10, //每页显示多少行数据
      total: 50, //数据总行数
      selectOption: [10, 20] //允许设置每页行数的选项
    },
    hook: {
      // 鼠标在表格落下执行
      cellDragStop (cell, position) {
        const { r, c } = position;
        if (!(cell && cell.v) && dragTargetNode.value) {
          const mv = {
            m: "{{" + dragTargetNode.value.name + "}}",
            v: "{{" + dragTargetNode.value.name + "}}",
            ct: {
              fa: "General",
              t: "g"
            },
            agg: 'list',
            cro: 'down',
          };
          if (dragTargetNode.value.source && dragTargetNode.value.key) {
            mv.sk = dragTargetNode.value.source + "." + dragTargetNode.value.key;
          }
          luckysheet.setCellValue(r, c, { ...mv, key: dragTargetNode.value.key, source: dragTargetNode.value.source });
          dragTargetNode.value = null;
          // initData();
        }
      },
      // 点击单元格触发
      cellMousedownBefore (cell, position) {
        cellBody.value = {
          cell: cell || {},
          position,
        }
      },
      onTogglePager () {
        console.log('onTogglePager')
      }
    },
    data: [
      {
        name: "Sheet-" + new Date(), //工作表名称
        defaultRowHeight: 30, //自定义行高
        defaultColWidth: 150, //自定义列宽
        data: sheetDataValue || sheetData,
        config,
      },
    ],
  });
}

const initData = () => {
  console.log('开始获取后台结构数据...');
  const data = {
    'q.1': [1, 2, 3, 4, 5, 6, 7, 8, 10]
  };
  console.log('开始获取lucksheet模板...');
  const sheetData = JSON.parse(localStorage.getItem('LUCKSHEET_SHEETDATA')) || [];
  // console.log(sheetData);
  console.log('模板引擎解析器开始工作...');
  if (sheetData && sheetData.length > 0) {
    sheetData.forEach(row => {
      console.log(row)
    });
  }

  console.log('模板引擎解析完成，开始渲染工作');
}

watch(() => cellBody.value, () => {
  // console.log(cellBody.value)
})
</script>

<style  scoped>
#luckysheet {
  position: absolute;
  padding: 0px;
  margin: 0px;
  left: 0px;
  top: 0px;
  width: 100%;
  height: 100%;
}

.w-full {
  width: 100% !important;
}

.h-full {
  height: 100% !important;
}

.mb-1 {
  margin-bottom: 1em;
}
</style>
